/**
 * @example SDLvncviewer.c
 */

#include "SDL_Tools.h"

void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
    int bpp = surface->format->BytesPerPixel;
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

    switch(bpp) {
    case 1:
        *p = pixel;
        break;

    case 2:
        *(Uint16 *)p = pixel;
        break;

    case 3:
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
            p[0] = (pixel >> 16) & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = pixel & 0xff;
        } else {
            p[0] = pixel & 0xff;
            p[1] = (pixel >> 8) & 0xff;
            p[2] = (pixel >> 16) & 0xff;
        }
        break;

    case 4:
        *(Uint32 *)p = pixel;
        break;
    }
}

void putPixelAndUpdate(SDL_Surface *surface, int x, int y, Uint32 pixel){
	 if ( SDL_MUSTLOCK(surface) ) {
		if ( SDL_LockSurface(surface) < 0 ) {
			fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
			return;
		}
	}

	putpixel(surface, x, y, pixel);

	if ( SDL_MUSTLOCK(surface) ) {
		SDL_UnlockSurface(surface);
	}
	SDL_UpdateRect(surface, x, y, 1, 1);
}
void drawFullSurface(SDL_Surface *surface,  Uint32 pixel){
	int w = surface->w;
	int h = surface->h;
	int x, int y;
	for (x = 0; x < w; ++x) {
		for (y = 0; y < h; ++x) {
			putpixel(surface, x, y, pixel);
		}
	}
}
void drawFullSurfaceAndUpdate(SDL_Surface *surface, Uint32 pixel){
	 if ( SDL_MUSTLOCK(surface) ) {
		if ( SDL_LockSurface(surface) < 0 ) {
			fprintf(stderr, "Can't lock screen: %s\n", SDL_GetError());
			return;
		}
	}
	drawFullSurface(surface,pixel)

	if ( SDL_MUSTLOCK(surface) ) {
		SDL_UnlockSurface(surface);
	}
	SDL_UpdateRect(surface, 0, 0, 0, 0);
}

